<?php

namespace app\merchant\controller;

use app\common\controller\Platurl;
use app\common\controller\TestBase;
use app\common\model\LoginCode;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\AuthRole;
use app\common\model\DictItem;
use app\common\model\MerchantCashier;
use app\common\controller\AdminBase;
use think\Db;
use think\Request;
use think\Session;
use thinkcms\auth\model\AuthRoleUser;


class Personneltest extends TestBase
{

    //收银员列表
    public function cashierlist()
    {
        $request = request();
        $p_data = $request->get();
        $map = [];
        if ($p_data) {
            if ($p_data['xingming']) {
                $map['xingming'] = array('like', '%' . trim($p_data['xingming']) . '%');
            } else {
                $p_data['xingming'] = '';
            }
            $p_data['merchant'] = '';
        } else {
            $p_data['mid'] = $this->get_mer_mid();
            $p_data['xingming'] = '';
        }
        $mer_mid = $this->get_mer_mid();
        if($mer_mid!==''){
            $smerid = explode(',', $mer_mid);
            $len = count($smerid);
            if ($len > 1){
                foreach($smerid as $k=>$v){
                    $msid[]=array(array('like','%,'.$v),array('like',$v.',%'),array('like','%,'.$v.',%'),array('eq',$v),'or');
                }
                $map['mid']=array($msid,'or');
            }else{
                $map['mid']=$mer_mid;
            }
        }else{
            $map['mid']=0;
        }
        $LoginUsers = new LoginUsers();
        $list = $LoginUsers->where($map)->select();
        $this->assign('p_data', $p_data);
        $this->assign('list', $list);
        if (Session::get('login_top_mid') !== 1){
            $this->unbinlist($list);
        }
        return $this->fetch();

    }

    private function unbinlist($list){
        if ($list){
            $Merchant = new Merchant();
            $LoginUsers = new LoginUsers();
            $machtpl_type = $Merchant->where(['top_mid'=>Session::get('login_top_mid')])->value('tpl_msg_type');
            foreach ($list as $k=>$v){
                if ($v['tpl_msg_type'] !== $machtpl_type){
                    $data[$k]['id'] = $v['id'];
                    $data[$k]['openid'] = '';
                    $data[$k]['headimg'] = '';
                    $data[$k]['nickname'] = '';
                }
            }
            if (isset($data)){
                $res = $LoginUsers->saveAll($data);
//                var_dump(json_encode($data));
//                var_dump(json_encode($res));
            }
        }
    }

    //用户添加
    public function cashieradd()
    {
        $request = request()->post();
        if (Request()->isPost()) {
            if (isset($request['mid'])) {
                $level = $request['level'];
                $data['xingming'] = $request['xingming'];
                $data['tel'] = $request['tel'];
                $data['gonghao'] = $request['gonghao'];
                $data['username'] = $request['username'];
                $data['password'] = MD5($request['password']);
                $data['level'] = $level;
                $mid = implode(",", $request['mid']);
                $data['mid'] = $mid;
                $data['MerchantCashier'] = [
                    'mid' => $request['mid'],
                    'gonghao' => $request['gonghao'],
                    'xingming' => $request['xingming'],
                    'level' => $request['level'],
                    'tel' => $request['tel'],
                    'is_tz' => 1,
                    'create_time' => time(),
                ];
                $LoginUser = new LoginUsers();
                $sav = $LoginUser->together('MerchantCashier')->validate("LoginUsers.add")->save($data);
                if ($sav) {
                    switch ($level) {
                        case "3001":
                            $roleid = 4;
                            break;
                        case "3002":
                            $roleid = 5;
                            break;
                        case "3003":
                            $roleid = 6;
                            break;
                        case "3004":
                            $roleid = 9;
                            break;
                    }
                    $sdata['role_id'] = $roleid;
                    $sdata['user_id'] = $LoginUser->id;
                    $AuthRoleUser = new AuthRoleUser();
                    $AuthRoleUser->save($sdata);
                    $this->success("添加成功", url('personnel/cashierlist'));
                } else {
                    $this->error($LoginUser->getError());
                }
            }else{
                $this->error('请添加门店后再添加人员');
            }
        } else {
            $DictItem = new DictItem();
            if (Session::get('level')=='3002'){
                $dice = $DictItem->where(['value' => 3003])->select();
            }else {
                $map['value'] = ['in','3002,3003'];
                $dice = $DictItem->where($map)->select();
            }
            $mab['id'] = array('in', $this->get_mer_mid());
            $Merchant = new Merchant();
            $mach = $Merchant->where($mab)->select();
            $this->assign('mach', $mach);
            $this->assign('dice', $dice);
            return $this->fetch();
        }
    }

    //授权检查
    public function chackcashier(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
            $LoginCode = new LoginCode();
            $code = $LoginCode->where(['action' => 'bangding', 'code' => $param['scode']])->find();
            if ($code) {
                $code['userinfo'] = json_decode($code['userinfo'], true);
                if ($code['status'] == 2) {
                    if ($code['userinfo']) {
                        $rarr['data'] = $code['userinfo'];
                        $rarr['code'] = 0;
                        $rarr['message'] = 'success';
                    } else {
                        $rarr['data'] = $code['userinfo'];
                        $rarr['code'] = 9001;
                        $rarr['message'] = 'error';
                    }
                } else {
                    $rarr['data'] = '';
                    $rarr['code'] = 9002;
                    $rarr['message'] = 'error';
                }
            }else{
                $rarr['data'] = '';
                $rarr['code'] = 9003;
                $rarr['message'] = 'error';
            }
            return json($rarr);
        }
    }

    //收银员绑定
    public function cashierbinding()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $LoginUser = new LoginUsers();
            $only = $LoginUser->where('openid', $arr['openid'])->value('id');
            if (empty($only)) {
                $data = [
                    "openid" => $arr['openid'],
                    "headimg" => $arr['headimg'],
                    "nickname" => $arr['nickname'],
                ];
                $Platurl = new Platurl();
                $Merchat = new Merchant();
                $mid = $Merchat->where(['top_mid'=>Session::get('login_top_mid')])->value('id');
                $msgtype = $Platurl->getagenttplmsgtype($mid);
                switch ($msgtype){
                    case 2:
                        $data['agent_openid'] = $arr['openid'];
                        $data['tpl_msg_type'] = $msgtype;
                        break;
                    case 3:
                        $data['mach_openid'] = $arr['openid'];
                        $data['tpl_msg_type'] = $msgtype;
                        break;
                    default:
                        $data['openid'] = $arr['openid'];
                        $data['tpl_msg_type'] = $msgtype;
                        break;
                }
                $resu = $LoginUser->save($data, ['id' => $arr['uid']]);
                $Cashier = new MerchantCashier();
                $Cashier->save(['openid'=>$arr['openid']],['uid'=>$arr['uid']]);
                if ($resu) {
                    $rarr['code'] = 0;
                    $rarr['message'] = "绑定成功！";
                    $rarr['type'] = $msgtype;
                } else {
                    $rarr['code'] = 9001;
                    $rarr['message'] = "绑定失败！";
                }
            } else {
                $rarr['code'] = 9002;
                $rarr['message'] = "您已经绑定其他门店";
            }
            return json($rarr);
        }
    }

    //可退款门店列表
    public function per_machlist()
    {
        if (request()->isAjax()) {
            $map['id'] = array('in', $this->get_mer_mid());
            $Merchant = new Merchant();
            $list = $Merchant->where($map)->field('id,merchant')->select();
            foreach ($list as $k => $v) {
                $list[$k]['is_tz'] = $this->check_tz(request()->post('openid'), $v['id']);
            }
            return json($list);
        }
    }

    //检查退款
    private function check_tz($openid, $mid)
    {
        $mab['openid'] = $openid;
        $mab['mid'] = $mid;
        $Cashier = new MerchantCashier();
        $s = $Cashier->where($mab)->find();
        if ($s) {
            $data['is_tz'] = $s['is_tz'];
        } else {
            $data['is_tz'] = 0;
        }
        return $data;
    }

    //k开启关闭收银通知方法
    public function add_cashier()
    {
        if (request()->isAjax()) {
            $mab['openid'] = request()->post('openid');
            $mab['mid'] = request()->post('mid');
            $Cashier = new MerchantCashier();
            $s = $Cashier->where($mab)->find();
            if ($s) {
                $data['is_tz'] = request()->post('is_tz');
                $s = $Cashier->save($data, ['id' => $s['id']]);
            } else {
                $LoginUser = new LoginUsers();
                $userinfo = $LoginUser->where(['openid' => request()->post('openid')])->find();
                $data['openid'] = request()->post('openid');
                $data['mid'] = request()->post('mid');
                $data['xingming'] = $userinfo['xingming'];
                $data['level'] = $userinfo['level'];
                $data['uid'] = $userinfo['id'];
                $data['is_tz'] = request()->post('is_tz');
                $s = $Cashier->save($data);
            }
            if ($s) {
                $arr = array('code' => 0, 'message' => "操作成功");
            } else {
                $arr = array('code' => 1, 'message' => "操作失败");
            }
            return json($arr);
        }
    }

    //收银员解绑
    public function cashierunbin()
    {
        if (request()->isAjax()) {
            $id = request()->post('id');
            $LoginUser = new LoginUsers();
            $openid = $LoginUser->where('id', $id)->value('openid');
            $Cashier = new MerchantCashier();
            $Cashier->where(['openid' => $openid])->delete();
            $data['openid'] = '';
            $data['mach_openid'] = '';
            $data['agent_openid'] = '';
            $data['headimg'] = '';
            $data['nickname'] = '';
            $s2 = $LoginUser->save($data, ['id' => $id]);
            if ($s2) {
                $arr = array('code' => 0, 'message' => "解绑成功");
            } else {
                $arr = array('code' => 1, 'message' => "解绑失败");
            }
            return json($arr);
        }
    }


    //关闭/开启店长日报表通知
    public function offreport(){
        if (request()->isGet()){
            $arr = request()->param();
            $map['id'] = $arr['id'];
            $data['is_report'] = $arr['report'] == 0?1:0;
            $LoginUser = new LoginUsers();
            $res = $LoginUser->save($data,$map);
            if ($res){
                $msg = $data['is_report'] == 1?'已开启':'已关闭';
                $this->success($msg,url('personnel/cashierlist'));
            }else{
                $this->error('修改失败',url('personnel/cashierlist'));
            }
        }
    }

    //收银员修改
    public function cashieredit($id)
    {
        $request = request()->post();
        if (Request()->isPost()) {
            $level = $request['level'];
            $request['id'] = $id;
            $data['xingming'] = $request['xingming'];
            $data['tel'] = $request['tel'];
            $data['gonghao'] = $request['gonghao'];
            if (!empty($request['password']))
                $data['password'] = MD5($request['password']);
            $data['level'] = $level;
            $mid = implode(",", $request['mid']);
            $data['mid'] = $mid;
            $LoginUser = new LoginUsers();
            $sav = $LoginUser->allowField(true)->save($data, ['id' => $request['id']]);
            if ($sav) {
                switch ($level) {
                    case "3001":
                        $roleid = 4;
                        break;
                    case "3002":
                        $roleid = 5;
                        break;
                    case "3003":
                        $roleid = 6;
                        break;
                    case "3004":
                        $roleid = 9;
                        break;
                }
                $datas['gonghao'] = $request['gonghao'];
                $datas['xingming'] = $request['xingming'];
                $datas['level'] = $request['level'];
                $datas['tel'] = $request['tel'];
                $MerchantCashier = new MerchantCashier();
                $MerchantCashier->allowField(true)->save($datas, ['uid' => $request['id']]);
                $sdata['role_id'] = $roleid;
                $AuthRoleUser = new AuthRoleUser();
                $AuthRoleUser->save($sdata, ['user_id' => $request['id']]);
                $this->success("修改成功",url('personnel/cashierlist'));
            } else {
                $this->error("修改失败",url('personnel/cashierlist'));
            }
        } else {
            $MerchantCashier = new MerchantCashier();
            $map['uid'] = $id;
            $machp['id'] = array('in', $this->get_mer_mid());
            $DictItem = new DictItem();
            $Merchant = new Merchant();
            $LoginUser = new LoginUsers();
            $loguser = $LoginUser->where('id', $id)->find();
            $mach = $Merchant->where($machp)->select();
            $cashier = $MerchantCashier->where('uid', $loguser['id'])->find();
            $dice = $DictItem->where('type_id', 4)->select();
            $this->assign('cashier', $cashier);
            $this->assign('mach', $mach);
            $this->assign('dice', $dice);
            $this->assign('loguser', $loguser);
            return $this->fetch();
        }
    }

    //员工删除
    public function cashierdel()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $LoginUser = new LoginUsers();
            $LoginUser = $LoginUser::get($arr['id']);
            $res = $LoginUser->together('MerchantCashier')->delete();
            if ($res) {
                $rarr = [
                    'code' => 0,
                    'mesg' => "删除成功！"
                ];
            } else {
                $rarr = [
                    'code' => 9001,
                    'mesg' => "删除失败！"
                ];
            }
            return json($rarr);
        }
    }

    //重置密码
    public function resetpassword(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $LoginUsers = new LoginUsers();
            $password = $this->getrandmopassword(8);
            $data['password'] = MD5($password);
            $res = $LoginUsers->allowField(true)->save($data,array('username'=>$arr['username']));
            if ($res){
                $rarr['code'] = 0;
                $rarr['message'] = '重置成功';
                $rarr['username'] = $arr['username'];
                $rarr['new_password'] = $password;
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '重置失败';
            }
            return json($rarr);
        }
    }

    //生成随机密码
    private function getrandmopassword($len, $chars=null){
        if (is_null($chars)){
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    //获取收银员详情
    public function getcashier_info()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $LoginUser = new LoginUsers();
            $datas = $LoginUser->where($map)->find();
            $str_rand = $this->generate_code();
            $LoginCode = new LoginCode();
            $LoginCode->save(['code' => $str_rand, 'addtime' => time(), 'action' => 'bangding']);
            $login_url = "https://" . $_SERVER['HTTP_HOST'] . url('login/authbangding', ['scode' => $str_rand, 'id' => request()->post('id'),'top_mid'=>Session::get('login_top_mid')]);
            $xml = '<?xml version="1.0" encoding="utf-8"?>
                    <request>
                    <type>codebangding</type>
                    <code>' . $str_rand . '</code> 
                    </request>
                ';
            $data = array('xingming' => $datas['xingming'], 'gonghao' => $datas['gonghao'], 'code' => $str_rand, 'shuju' => $xml, 'login_url' => $login_url);
            return json($data);
        }
    }

    //获取50位随机字符串
    private function generate_code($length = 50)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-';
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $code;
    }
}
